#!/bin/bash

# 确保日志函数
log() {
    # echo "[INFO] $1"
    :
}

# 检查并安装 curl
check_and_install_curl() {
    if ! command -v curl &> /dev/null; then
        log "curl 未找到，正在安装..."
        
        # 检查是否为 root 用户
        if [ "$EUID" -eq 0 ]; then
            install_cmd=""
        else
            install_cmd="sudo"
        fi

        if command -v apt-get &> /dev/null; then
            $install_cmd apt-get update
            $install_cmd apt-get install -y curl
        elif command -v yum &> /dev/null; then
            $install_cmd yum install -y curl
        else
            log "不支持的包管理器，请手动安装 curl"
            exit 1
        fi
    else
        log "curl 已安装"
    fi
}

# 获取内核版本和架构
kernel_info=$(uname -a)
kernel_version=$(echo $kernel_info | awk '{print $3}')
architecture=$(echo $kernel_info | awk '{print $(NF-1)}')

# 获取操作系统信息
os_info=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d= -f2- | tr -d '"')
if [ -z "$os_info" ]; then
  os_info=$(grep '^NAME=' /etc/os-release | cut -d= -f2- | tr -d '"')
fi

# 获取内存信息
read -r total mem_used free shared cache available <<<$(LANG=C free -h | awk '/^Mem:/ {print $2, $3, $4, $5, $6, $7}')

# 获取CPU信息
cpu_model=$(LANG=C lscpu | grep -m1 'Model name:' | awk -F: '{print $2}' | xargs)
cpu_cores=$(LANG=C lscpu | grep -m1 '^CPU(s):' | awk '{print $2}')

# 获取GPU信息
gpus=()
while IFS=, read -r name memory; do
    gpus+=("{ \"name\": \"$name\", \"memory\": \"$memory\" }")
done < <(nvidia-smi --query-gpu=gpu_name,memory.total --format=csv,noheader,nounits)

# 获取CUDA信息
nvidia_smi_cuda=$(nvidia-smi | grep -oP 'CUDA Version: \K[\d.]+')
nvcc_version=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+')

# 获取CuDNN信息
cudnn_version=$(grep -E "#define CUDNN_(MAJOR|MINOR|PATCHLEVEL)" /usr/include/cudnn*.h 2>/dev/null | \
  awk '/CUDNN_MAJOR/{major=$3} /CUDNN_MINOR/{minor=$3} /CUDNN_PATCHLEVEL/{patch=$3} END {if (major != "" && minor != "" && patch != "") print major"."minor"."patch; else print "null"}')

# 获取磁盘信息
disk_info=$(df -B1 --output=size,used,avail,target | awk 'NR>1')
total_size=0
total_used=0
total_available=0
while read -r size used avail target; do
  if [ "$target" = "/" ] || [[ "$target" == /home* ]]; then
    total_size=$(awk "BEGIN {print $total_size + $size}")
    total_used=$(awk "BEGIN {print $total_used + $used}")
    total_available=$(awk "BEGIN {print $total_available + $avail}")
  fi
done <<<"$disk_info"

# Convert bytes to GB
total_size_gb=$(awk "BEGIN {printf \"%.2f\", $total_size/1024/1024/1024}")
total_used_gb=$(awk "BEGIN {printf \"%.2f\", $total_used/1024/1024/1024}")
total_available_gb=$(awk "BEGIN {printf \"%.2f\", $total_available/1024/1024/1024}")
disk_percent=$(awk "BEGIN {printf \"%.2f\", ($total_used/$total_size)*100}")

# 获取软件信息

# 设置软件安装目录
conda_dir="$HOME/.labelapp/miniconda"
node_dir="$HOME/.labelapp/nodejs"
labelapp_dir="$HOME/.labelapp/labelapp"
root_dir="$HOME/.labelapp"
BOS_BASE_URL="https://label-anything.bd.bcebos.com/labelapp/server"
REMOTE_INDEX_URL="${BOS_BASE_URL}/VERSION"

# 获取 Python 目录，过滤掉 miniconda
python_dir=$(env PATH="$(echo $PATH | tr ':' '\n' | grep -v 'miniconda' | tr '\n' ':')" which python3 2>/dev/null)

# 获取 conda 版本
conda_version=$(eval "$conda_dir/bin/conda --version" 2>/dev/null)
conda_version=$(echo "$conda_version" | sed "s/^conda\s*//")

# 获取 node 版本
node_version=$(eval "$node_dir/bin/node -v" 2>/dev/null)
node_version=$(echo "$node_version" | sed "s/^v//")

# 获取 python 版本
python_version=$(eval "env PATH=\"$(echo $PATH | tr ':' '\n' | grep -v 'miniconda' | tr '\n' ':')\" python3 --version" 2>/dev/null)
python_version=$(echo "$python_version" | sed "s/^Python\s*//")

# 获取 labelapp 版本
labelapp_version=$(eval "cat $root_dir/VERSION" 2>/dev/null)
labelapp_version=$(echo "$labelapp_version" | sed "s/^\s*//")

# 处理软件输出格式的函数
format_software_entry() {
  local name="$1"
  local version="$2"
  local directory="$3"
  if [[ "$version" == "" ]]; then
    echo "\"$name\": null"
  else
    echo "\"$name\": {
      \"version\": \"$version\",
      \"directory\": \"$directory\"
    }"
  fi
}

# 格式化软件版本输出格式
conda_entry=$(format_software_entry "conda" "$conda_version" "$conda_dir")
node_entry=$(format_software_entry "node" "$node_version" "$node_dir")
python_entry=$(format_software_entry "python" "$python_version" "${python_dir:-null}")
labelapp_entry=$(format_software_entry "labelapp" "$labelapp_version" "$labelapp_dir")

# 判断labelapp是否正在正在运行
labelapp_status="stop"  # 默认设置为 "stop"
if pgrep -f "${node_dir}/bin/node start.js" > /dev/null; then
  labelapp_status="running"
fi

# 读取labelapp的版本信息
get_remote_version() {
    curl -s $REMOTE_INDEX_URL | tr -d '\n'
}

get_local_version() {
    if [ -f "$root_dir/VERSION" ]; then
        cat "$root_dir/VERSION" | tr -d '\n'
    else
        echo ""
    fi
}
check_and_install_curl
remote_version=$(get_remote_version)
local_version=$(get_local_version)

# 获取 Conda 环境列表
get_conda_env_list() {
    local env_list_output
    env_list_output=$("$conda_dir/bin/conda" env list 2>/dev/null)
    echo "$env_list_output" | awk 'NR>2 && NF>=2 { if ($2 == "*") { print "{\"name\": \"" $1 "\", \"path\": \"" $3 "\"}"} else { print "{\"name\": \"" $1 "\", \"path\": \"" $2 "\"}"}}' | paste -sd ',' -
}

# 获取 Conda 环境 JSON 格式
conda_env_json=$(get_conda_env_list)

# 构建JSON输出
json_output=$(cat <<EOF
{
    "kernelVersion": "$kernel_version",
    "architecture": "$architecture",
    "osInfo": "$os_info",
    "memoryInfo":
    {
        "total": "$total",
        "used": "$mem_used",
        "free": "$free",
        "shared": "$shared",
        "cache": "$cache",
        "available": "$available"
    },
    "cpuInfo":
    {
        "cpuModel": "$cpu_model",
        "cpuCores": $cpu_cores
    },
    "gpuInfo": [
        $(IFS=,; echo "${gpus[*]}")
    ],
    "cudaInfo":
    {
        "nvidiaSmiCUDA": "$nvidia_smi_cuda",
        "nvccVersion": "${nvcc_version:-null}"
    },
    "cuDnnInfo":
    {
        "version": "${cudnn_version:-null}"
    },
    "diskInfo":
    {
        "totalSize": "${total_size_gb}G",
        "totalUsed": "${total_used_gb}G",
        "totalAvailable": "${total_available_gb}G",
        "percent": "${disk_percent}%"
    },
    "software":
    {
        $conda_entry,
        $node_entry,
        $python_entry,
        $labelapp_entry
    },
    "condaEnvs": [
        $conda_env_json
    ],
    "labelapp":
    {
        "status": "${labelapp_status}",
        "newVersion": "$remote_version",
        "installVersion": "$local_version"
    }
}
EOF
)

# 输出JSON结果
echo "$json_output"